﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Web;

namespace CatUtils.Utils.SpecialUtils.Spider
{
    /// <summary>
    /// 对原生IE的获取COOKIES操作辅助工具类
    /// </summary>
    public class CookiesTool
    {
#pragma warning disable S101 // Types should be named in PascalCase

        #region enums

#pragma warning disable S2344 // Enumeration type names should not have "Flags" or "Enum" suffixes

#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释

        public enum ErrorFlags

        {
            ERROR_INSUFFICIENT_BUFFER = 122,
            ERROR_INVALID_PARAMETER = 87,
            ERROR_NO_MORE_ITEMS = 259
        }

        public enum InternetFlags
#pragma warning restore S2344 // Enumeration type names should not have "Flags" or "Enum" suffixes
        {
            INTERNET_COOKIE_HTTPONLY = 8192, //Requires IE 8 or higher
            INTERNET_COOKIE_THIRD_PARTY = 131072,
            INTERNET_FLAG_RESTRICTED_ZONE = 16
        }

        #endregion enums

        #region DLL Imports

        [SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("wininet.dll", EntryPoint = "InternetGetCookieExW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
#pragma warning disable S4200 // Native methods should be wrapped
#pragma warning disable S4214 // "P/Invoke" methods should not be visible
        public static extern bool InternetGetCookieEx([In] string Url, [In] string cookieName, [Out] StringBuilder cookieData, [In, Out] ref uint pchCookieData, uint flags, IntPtr reserved);

#pragma warning restore S4200 // Native methods should be wrapped

        #endregion DLL Imports

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
#pragma warning disable S4200 // Native methods should be wrapped
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetOption(double hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);

#pragma warning restore S4200 // Native methods should be wrapped
#pragma warning restore S4214 // "P/Invoke" methods should not be visible
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
        /* SOURCE: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx  *
               INTERNET_OPTION_SUPPRESS_BEHAVIOR (81):  *   A general purpose option that is used to suppress behaviors on a process-wide basis.   *   The lpBuffer parameter of the function must be a pointer to a DWORD containing the specific behavior to suppress.   *   This option cannot be queried with InternetQueryOption.   *     * INTERNET_SUPPRESS_COOKIE_PERSIST (3):  *   Suppresses the persistence of cookies, even if the server has specified them as persistent.  *   Version: Requires Internet Explorer 8.0 or later.  */
        /*注释掉不安全的代码 这个功能仅在需要时才用ingl
 /// <summary>
 /// 清理所有Cookies
 /// </summary>
 public unsafe void SuppressWininetBehavior()
 {
     int option = (int)3;//INTERNET_SUPPRESS_COOKIE_PERSIST
     int* optionPtr = &option;
     bool success = InternetSetOption(0, 81, new IntPtr(optionPtr), sizeof(int));//INTERNET_OPTION_SUPPRESS_BEHAVIOR
     if (!success) { MessageBox.Show("Something went wrong !>?"); }
 }*/

        /// <summary>
        /// 设置Cookies Webbower提供的即可
        /// </summary>
        /// <param name="Link"></param>
        /// <param name="Cookies"></param>
        public void SetCookies(string Link, string Cookies)

        {
            string cookie = Cookies;//需要设置到Webbrowser的Cookie信息
            string url = Link;

            foreach (string c in cookie.Split(';'))
            {
                string[] item = c.Split('=');
                if (item.Length == 2)
                {
                    InternetSetCookie(url, null, new Cookie(HttpUtility.UrlEncode(item[0]).Replace("+", ""), HttpUtility.UrlEncode(item[1]),
                          "; expires = Session GMT", "/").ToString());
                }
            }
        }

        /// <summary>
        /// 清理Cookies信息  Webbower提供的即可 将value设置为“”
        /// </summary>
        /// <param name="Link"></param>
        /// <param name="Cookies"></param>
        public void ClearCookies(string Link, string Cookies)

        {
            string cookie = Cookies;//需要设置到Webbrowser的Cookie信息
            string url = Link;

            foreach (string c in cookie.Split(';'))
            {
                string[] item = c.Split('=');
                if (item.Length == 2)
                {
                    InternetSetCookie(url, null, "");
                }
            }
        }

        /// <summary>
        /// 获取COOKIES列表
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="throwIfNoCookie"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetCookieList(Uri uri, bool throwIfNoCookie)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string cookie = GetCookiepublic(uri, throwIfNoCookie);
            Console.WriteLine("FullWebBrowserCookie - 所有cookie:" + cookie);
            string[] arrCookie = cookie.Split(';');
            foreach (var item in arrCookie)
            {
                string[] arr = item.Split('=');
                string key = arr[0].Trim();
                string val = "";
                if (arr.Length >= 2)
                {
                    val = arr[1].Trim();
                }

                if (!dict.ContainsKey(key))
                {
                    dict.Add(key, val);
                }
            }
            Console.WriteLine("FullWebBrowserCookie - cookie已载入dict，共" + dict.Count.ToString() + "项");

            return dict;
        }

        /// <summary>
        /// 获取单个COOKIES
        /// </summary>
        /// <param name="key"></param>
        /// <param name="uri"></param>
        /// <param name="throwIfNoCookie"></param>
        /// <returns></returns>
        public string GetCookieValue(string key, Uri uri, bool throwIfNoCookie)
        {
            Console.WriteLine("GetCookieValue");
            Dictionary<string, string> dict = GetCookieList(uri, throwIfNoCookie);

            if (dict.ContainsKey(key))
            {
                return dict[key];
            }
            return "";
        }

        /// <summary>
        /// 获取可直接用于赋值的COOKIES
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="throwIfNoCookie"></param>
        /// <returns></returns>
        public WebHeaderCollection GetWebHeaderCollection(Uri uri, bool throwIfNoCookie)
        {
            Dictionary<string, string> dict = GetCookieList(uri, throwIfNoCookie);
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
            foreach (var item in dict)
            {
                webHeaderCollection.Add(item.Key, item.Value);
            }
            return webHeaderCollection;
        }

        /// <summary>
        /// 获取Cookies
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="throwIfNoCookie"></param>
        /// <returns></returns>
        [SecurityCritical]
        public string GetCookiepublic(Uri uri, bool throwIfNoCookie)
        {
            uint pchCookieData = 0;
            string url = UriToString(uri);
            uint flag = (uint)InternetFlags.INTERNET_COOKIE_HTTPONLY;

            //Gets the size of the string builder
            if (InternetGetCookieEx(url, null, null, ref pchCookieData, flag, IntPtr.Zero))
            {
                pchCookieData++;
                StringBuilder cookieData = new StringBuilder((int)pchCookieData);

                //Read the cookie
                if (InternetGetCookieEx(url, null, cookieData, ref pchCookieData, flag, IntPtr.Zero))
                {
                    DemandWebPermission(uri);
                    return cookieData.ToString();
                }
            }

            int lastErrorCode = Marshal.GetLastWin32Error();

            if (throwIfNoCookie || (lastErrorCode != (int)ErrorFlags.ERROR_NO_MORE_ITEMS))
            {
                Console.WriteLine(new Win32Exception(lastErrorCode).Message);
            }

            return "";
        }

        private void DemandWebPermission(Uri uri)
        {
            string uristring = UriToString(uri);

            if (uri.IsFile)
            {
                string localPath = uri.LocalPath;
                new FileIOPermission(FileIOPermissionAccess.Read, localPath).Demand();
            }
            else
            {
                new WebPermission(NetworkAccess.Connect, uristring).Demand();
            }
        }

        private string UriToString(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            UriComponents components = (uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString);
            return new StringBuilder(uri.GetComponents(components, UriFormat.SafeUnescaped), 2083).ToString();
        }
    }
}